<template>
  <view class="wrap">
    <view class="turtle_mes">
      <view class="inp_box">
        <input
          class="form_inp pa-input"
          v-model="formData.turtle_name"
          focus
          placeholder="输入爱龟的名字或编号"
        />
      </view>

      <view class="inp_box">
        <input
          class="form_inp pa-input"
          v-model="formData.turtle_varieties"
          placeholder="输入爱龟的品种"
        />
      </view>

      <view class="inp_box">
        <view class="uni-list">
          <view class="uni-list-cell">
            <view class="uni-list-cell-left">出壳日期</view>
            <view class="uni-list-cell-db">
              <picker
                mode="date"
                :value="date"
                :start="startDate"
                :end="endDate"
                @change="bindDateChange"
                fields="month"
              >
                <view class="uni-input date_text">{{ date }}</view>
              </picker>
            </view>
          </view>
        </view>
      </view>

      <view class="inp_box load_box" @click="upload">
        <image
          class="add_record_img"
          :style="!imageUrl && 'border: none'"
          :src="imageUrl ? imageUrl : '../../static/record/add.png'"
          mode="aspectFill"
        />
        <view class="upload_text">上传龟的照片,作为头像</view>
      </view>
    </view>
    <view v-if="isEdit" class="add_turtle" @click="editRecord">保存</view>
    <view v-else class="add_turtle" @click="addTurtle">提交</view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDate } from '@/utils/date.js'
import { authRequest } from '@/utils/authRequest.js'

// 响应式数据
const formData = reactive({
  turtle_name: "",
  turtle_varieties: ""
})

const imageUrl = ref("")
const date = ref(getDate({ format: true }))
const isEdit = ref(false)
const theId = ref()
// 计算属性
const startDate = computed(() => getDate('start'))
const endDate = computed(() => getDate('end'))

// 日期处理方法
const bindDateChange = e => {
  date.value = e.detail.value
  if (judgeDate(`${date.value}-01`) < 0) {
    uni.showToast({
      duration: 3000,
      icon: "none",
      title: "选择日期不能大于当前日期",
    })
    date.value = getDate({ format: true })
    return
  }
}

const judgeDate = tomodifyDate => 
  new Date().getTime() - new Date(tomodifyDate).getTime()

// 提交处理
const addTurtle = async () => {
  if (!formData.turtle_name || !formData.turtle_varieties || !date.value || !imageUrl.value) {
    uni.showToast({
      duration: 1000,
      icon: "none",
      title: "请补充完整信息后提交",
    })
    return
  }

  try {
    await authRequest('recordOfTurtle', {
      ...formData,
      turtle_age: date.value,
      image_url: imageUrl.value,
      user_id: uni.getStorageSync('userId')
    })

    uni.showToast({
      duration: 500,
      icon: "success",
      title: "添加成功",
    })
    
    setTimeout(() => {
      uni.navigateBack()
    }, 200)
  } catch (e) {
    console.error('提交失败:', e)
    uni.showToast({
      duration: 2000,
      icon: "none",
      title: "提交失败，请重试",
    })
  }
}

const editRecord = async () => {
  try {
    await authRequest('editRecord', {
      ...formData,
      _id: theId.value,
      turtle_age: date.value,
      image_url: imageUrl.value,
      user_id: uni.getStorageSync('userId')
    })

    uni.showToast({
      duration: 500,
      icon: "success",
      title: "编辑成功",
    })
    
    setTimeout(() => {
      uni.navigateBack()
    }, 200)
  } catch (e) {
    console.error('编辑失败:', e)
    uni.showToast({
      duration: 2000,
      icon: "none",
      title: "编辑失败，请重试",
    })
  }
}

// 图片上传
const upload = async () => {
  try {
    const res = await uni.chooseImage({})
    const [filePath] = res.tempFilePaths
    const fileInfo = res.tempFiles[0];
    const fileUnit = fileInfo.path.split('.')[1]
    
    uni.showLoading({ title: "上传中..." })
    
    const uploadRes = await uniCloud.uploadFile({
      filePath,
      cloudPath: `${Date.now()}-${res.tempFiles[0].name}`
    })
    
    imageUrl.value = uploadRes.fileID
    
    await authRequest("addImage", {
      imageUrl: uploadRes.fileID+'.'+fileUnit,
      createTime: Date.now()
    })
  } catch (e) {
    console.error('上传失败:', e)
    uni.showToast({
      duration: 2000,
      icon: "none",
      title: "上传失败，请重试",
    })
  } finally {
    uni.hideLoading()
  }
}


// 获取乌龟信息
const getTurtle = async (theId) => {
  try {
    const res = await authRequest('findTurtle', { _id: theId });
    
    if (res.result.code === 200) {
      const turtleMes = res.result.data.data[0];
      formData.turtle_name = turtleMes.turtle_name
      formData.turtle_varieties = turtleMes.turtle_varieties
      date.value = turtleMes.turtle_age
      imageUrl.value = turtleMes.turtle_url
      console.log(turtleMes, 'turtleMes')
    }
  } catch (e) {
    console.error('获取乌龟信息失败:', e);
    uni.showToast({ title: '获取乌龟信息失败', icon: 'none' });
  }
};

onLoad((options) => {
  if(options.id && options.type === 'edit') {
    uni.setNavigationBarTitle({
      title: '编辑信息'
    });
    getTurtle(options.id)
    theId.value = options.id
    isEdit.value = true
  }
})
</script>

<style lang="scss" scoped>
.wrap{
	width: 100%;
	min-height: 100vh;
	overflow-x: hidden;
    padding: 20rpx;
	box-sizing: border-box;
	.turtle_mes {
		width: 100%;
		padding: 20px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		.inp_box {
			width: 100%;
			padding-bottom: 20rpx;

			.add_record_img {
				width: 160rpx;
				height: 160rpx;
				border: 6rpx dashed #3d836d;
				padding: 6rpx;
				border-radius: 6rpx;
				&:view {
					border-radius: 6rpx;
				}
			}
			
			.uni-list {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				border: 1px solid #e5e5e5;
				color: #999;
				padding-left: 20rpx;
        box-sizing: border-box;
				.date_text {
					color: #333;
				}
				.uni-list-cell {
					display: flex;
				}
				.uni-list-cell-left {
					padding-right: 20rpx;
					font-size: 24rpx;
				}
			} 
		}
		.load_box {
			display: flex;
			flex-direction: column;
			align-items: center;
			.add_record_img {
				margin: 36rpx 0;
			}
		}
	}
	.add_turtle {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		background: #3d836d;
		color: #fff;
		border-radius: 20rpx;
		font-size: 32rpx;
	}

}
</style>
